package org.techism.client.panel;

import java.util.List;
import java.util.SortedMap;

import org.techism.client.PanelView;
import org.techism.client.TagPanelHelper;
import org.techism.client.bo.Group;
import org.techism.client.services.GroupService;
import org.techism.client.services.GroupServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;

public class GroupPanelView extends PanelView {
	/**
	 * Create a remote service proxy to talk to the server-side Group Service
	 */
	private final GroupServiceAsync groupService = GWT.create(GroupService.class);

	final HorizontalPanel tagPanel;
	final FlowPanel groupPanel;

	public GroupPanelView(final FlowPanel hPanel) {
		tagPanel = new HorizontalPanel();
		hPanel.add(tagPanel);
		groupPanel = new FlowPanel();
		hPanel.add(groupPanel);
	}

	public void addGroupTags() {
		groupService.getTags(new AsyncCallback<SortedMap<String, Integer>>() {
			public void onFailure(final Throwable caught) {
				showError();
			}

			public void onSuccess(final SortedMap<String, Integer> result) {
				final ClickHandler handler = new ClickHandler() {
					public void onClick(final ClickEvent event) {
						Anchor tag = (Anchor) event.getSource();
						final String text = tag.getText();
						if (text.equals("Alles anzeigen")) {
							selectGroups(null);
						} else {
							selectGroups(text);
						}
					}
				};
				TagPanelHelper.fillTagPanel(result, handler, tagPanel);
			}
		});
	}

	public void addGroups() {
		groupService.getAllGroups(new AsyncCallback<List<Group>>() {
			public void onFailure(final Throwable caught) {
				showError();
			}

			public void onSuccess(final List<Group> result) {
				for (final Group group : result) {
					processGroup(group);
				}
			}
		});
	}

	private void selectGroups(final String tag) {
		groupPanel.clear();
		groupService.getByTag(tag, new AsyncCallback<List<Group>>() {
			public void onFailure(final Throwable caught) {
				showError();
			}

			public void onSuccess(final List<Group> result) {
				for (final Group group : result) {
					processGroup(group);
				}
			}
		});
	}

	private void processGroup(final Group group) {
		groupPanel.add(new HTML("<br/>"));
		final Anchor anchor = new Anchor(group.getName(), group.getUrl());
		groupPanel.add(anchor);
		String tagString = "";
		for (final String tag : group.getTags()) {
			tagString += tag + ", ";
		}
		groupPanel.add(new Label(tagString));
		groupPanel.add(new HTML("<br/>"));
	}
}
